// Copyright (C) ustc9703
// All rights reserved.
// 
// Author : Jiang Li
// Date   : 2004-7-21

#include "stdafx.h"
#include "msgsocket.h"
#include "aes.h"

using namespace JoyMessage;

static BYTE s_aesKey[] =
{
    0x71, 0x89, 0x91, 0x97, 0x75, 0xAB, 0xD4, 0xC2,
    0xA1, 0x79, 0xD1, 0x47, 0x35, 0x79, 0x5C, 0xD6,
    0xB3, 0xB9, 0x31, 0x56, 0x77, 0xCC, 0x8E, 0xE9,
    0xC9, 0xE9, 0x11, 0xD3, 0x59, 0xEF, 0x9F, 0x3A,
};
CJoyAes s_msgCrypto(s_aesKey, sizeof(s_aesKey));

//##ModelId=44C4B5FC035F
CJoyMsgSocket::CJoyMsgSocket(void)
{
}

//##ModelId=44C4B5FC0361
CJoyMsgSocket::~CJoyMsgSocket(void)
{
}

//##ModelId=44C4B5FC0364
CJoySockSendData* CJoyMsgSocket::BuildJoyMsg(const JoyMessage::MessageBase* msg)
{
    CJoySockSendData* pSockMsg;
    if(msg->m_crypto)
    {
        UINT nCryptoSize = (msg->m_size-sizeof(MessageHeader)+15)&0xFFFFFFF0;
        UINT nSockMsgSize= nCryptoSize+sizeof(MessageHeader);
        
        pSockMsg = CJoySockSendData::Create(nSockMsgSize);
        memcpy(pSockMsg->GetData(), msg, msg->m_size);
        memset((BYTE*)pSockMsg->GetData()+msg->m_size, 0, nSockMsgSize-msg->m_size);
        BYTE* pCryptoBuf = (BYTE*)pSockMsg->GetData()+sizeof(MessageHeader);
        s_msgCrypto.Encrypt(pCryptoBuf, pCryptoBuf, nCryptoSize);
    }
    else
    {
        pSockMsg = CJoySockSendData::Create(msg, msg->m_size);
    }
    return pSockMsg;
}

//##ModelId=44C4B5FC036D
bool CJoyMsgSocket::SendJoyMsg(const JoyMessage::MessageBase* msg)
{
    CJoySockSendData* pSockMsg = BuildJoyMsg(msg);
    bool bRet = Send(pSockMsg);
    pSockMsg->Release();
    return bRet;
}

//##ModelId=44C4B5FC034F
void CJoyMsgSocket::OnJoyMsg(const JoyMessage::MessageBase* )
{
}

//##ModelId=44C4B5FC035B
void CJoyMsgSocket::OnBadJoyMsg(const void* , int )
{
}

//##ModelId=44C4B5FC036F
void CJoyMsgSocket::ProcessRecvData(const void* buf, int size)
{
    if(size < sizeof(JoyMessage::MessageBase))
    {
        OnBadJoyMsg(buf, size);
        return;
    }

    JoyMessage::MessageBase* msg = (JoyMessage::MessageBase*)buf;

    if((UINT)size < msg->m_size)
    {
        OnBadJoyMsg(buf, size);
        return;
    }

    if(msg->m_crypto)
    {
        int nCryptoSize = size-sizeof(MessageHeader);
        if((nCryptoSize&0x0000000F) != 0)
        {
            OnBadJoyMsg(buf, size);
            return;
        }
        BYTE* pCryptoBuf = (BYTE*)buf+sizeof(MessageHeader);
        s_msgCrypto.Decrypt(pCryptoBuf, pCryptoBuf, nCryptoSize);
    }

    OnJoyMsg(msg);
}

//##ModelId=44C4B5FC034C
void CJoyMsgSocket::OnRecvData(CJoySockRecvData& data)
{
    void* buf = data.GetData();
    int size = data.GetDataSize();

    ProcessRecvData(buf, size);
}
